import {
  TwinSpace2D,
  Geometry,
  ShaderMaterial,
  TSVector2,
  Mesh,
  TextureLoader,
  TSColor,
} from "twinspace2d";

import overLayFrag from "./shader/overLay.frag";
import overLayVert from "./shader/overLay.vert";

let WebPS2D = new TwinSpace2D("webglps");

const geometry = new Geometry();
const width = WebPS2D.canvas.clientWidth;
const height = WebPS2D.canvas.clientHeight;
geometry.setAttribute(
  "u_position",
  new Float32Array([
    0,
    0,
    width,
    0,
    width,
    height,
    width,
    height,
    0,
    height,
    0,
    0,
  ]),
  2
);

geometry.setAttribute(
  "uv",
  new Float32Array([0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0]),
  2
);

const material = new ShaderMaterial({
  uniforms: {
    u_resolution: {
      value: new TSVector2(
        WebPS2D.canvas.clientWidth,
        WebPS2D.canvas.clientHeight
      ),
    },
    u_color: {
      value: new TSColor("#ff0000"),
    },
    u_texture: {
      value: new TextureLoader().load("/public/background.jpg", (map) => {
        map.repeat = "repeat";
      }),
    },
    u_ratio: {
      value: new TSVector2(1, 1),
    },
    times: {
      value: 0,
    },
  },
  fragmentShader: overLayFrag,
  vertexShader: overLayVert,
});

const mesh = new Mesh(geometry, material);

window.addEventListener("resize", () => {
  material.uniforms.u_resolution.value = new TSVector2(
    WebPS2D.canvas.clientWidth,
    WebPS2D.canvas.clientHeight
  );

  material.uniforms.u_ratio.value = new TSVector2(
    width / WebPS2D.canvas.clientWidth,
    height / WebPS2D.canvas.clientHeight
  );
});

WebPS2D.scene.add(mesh);

const update = () => {
  requestAnimationFrame(update);
  WebPS2D.render();
};

update();
